package com.studyyoun.android.androidcommonbaselibrary.okhttp.client;

import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.https.HttpsUtils;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.qequest.OkhttpCommonRequest;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * Created by androidlongs on 17/6/28.
 * 站在顶峰，看世界
 * 落在谷底，思人生
 * <p>
 * <p>
 * <p>
 * okhttp client 封装
 */

public class OkhttpCommonClient {

    //设置超时时间
    private static final int TIME_OUT = 30;

    private static OkHttpClient sOkHttpClient;

    //设置client配置参数
    static {
        //创建 OkHttpClient.Builder
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        //设置超时时间
        builder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        builder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
        builder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);

        //允许重定向
        builder.followRedirects(true);


        //https 支持
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify (String s, SSLSession sslSession) {
                return true;
            }
        });

        builder.sslSocketFactory(HttpsUtils.getSslFactory());

        //初始化OKhttpClient
        sOkHttpClient = builder.build();
    }


    /**
     * 发送具体的http/https请求
     */
    private static Call sentRequest (Request request, OkhttpCommonCallBack callback) {
        Call call = sOkHttpClient.newCall(request);
        call.enqueue(callback);
        return call;
    }




    /**
     * 发送get请求
     */
    public static Call sentGetRequest (String url, ConcurrentHashMap<String, String>  map,OkhttpCommonCallBack callback) {

        Call call = sOkHttpClient.newCall(OkhttpCommonRequest.createGetRequest(url,map));
        call.enqueue(callback);
        return call;
    }
    /**
     * 发送Post请求
     */
    public static Call sentPostRequest (String url, ConcurrentHashMap<String, String>  map,OkhttpCommonCallBack callback) {

        Call call = sOkHttpClient.newCall(OkhttpCommonRequest.createPosRequest(url,map));
        call.enqueue(callback);
        return call;
    }
    /**
     * 发送Post File 请求
     */
    public static Call sentPostFileRequest (String url, ConcurrentHashMap<String, Object>  map,OkhttpCommonCallBack callback) {
        Call call = sOkHttpClient.newCall(OkhttpCommonRequest.createPosFileRequest(url,map));
        call.enqueue(callback);
        return call;
    }


}
